const STORAGE_KEY = {
  // App productLabel
  MALL_APP_PRODUCTLABEL: 'MALL_APP_PRODUCTLABEL',
  // app version
  MALL_APP_VERSION: 'MALL_APP_VERSION'
}

const storage = {
  set (key, value) {
    try {
      if (typeof value === 'object') {
        value = JSON.stringify(value)
      }
      window.localStorage.setItem(key, value)
    } catch (e) {
      console.log(e)
    }
  },
  get (key) {
    try {
      let s = window.localStorage.getItem(key)
      try {
        return JSON.parse(s)
      } catch (e) {
        return s
      }
    } catch (e) {
      return ''
    }
  },
  del (key) {
    try {
      window.localStorage.removeItem(key)
    } catch (e) {
      console.log(e)
    }
  },
  clean () {
    try {
      window.localStorage.clear()
    } catch (e) {
      console.log(e)
    }
  }
}

const getQueryMap = (queryString) => {
  let paramObj = {},
    paramList,
    oneQueryMatch,
    regGlobal = /[\?\&][^\?\&]+=[^\?\&#]+/g,
    regOne = /[\?\&]([^=\?]+)=([^\?\&#]+)/

  if(process.browser){
    queryString = queryString || location.href
  }else{
    queryString = queryString
  }
    
  if(!queryString){
    return {}
  }
  paramList = queryString.match(regGlobal)

  if (!paramList) {
    return paramObj
  }

  for (let i = 0, len = paramList.length; i < len; i++) {
    oneQueryMatch = paramList[i].match(regOne)
    if (null === oneQueryMatch) {
      continue
    }
    paramObj[oneQueryMatch[1]] = decodeURIComponent(oneQueryMatch[2])
    if (/(\%[0-9A-Z]{2})/.test(paramObj[oneQueryMatch[1]])) {
      paramObj[oneQueryMatch[1]] = decodeURIComponent(paramObj[oneQueryMatch[1]])
      if (/(\%[0-9A-Z]{2})/.test(paramObj[oneQueryMatch[1]])) {
        paramObj[oneQueryMatch[1]] = decodeURIComponent(paramObj[oneQueryMatch[1]])
      }
    }
  }
  return paramObj
}

const checkIsAssignEnv = (envUA) => {
  if(process.browser){
    const ua = window.navigator.userAgent.toUpperCase()
    return ua.indexOf(envUA) !== -1
  }else return false
 
}

const isApp = () => {
  const params = getQueryMap()
  const appChannel = params && params.appChannel || ''
  return appChannel && appChannel.toUpperCase() === 'APP'
}


const nativeCheck = {
  IS_NATIVE: checkIsAssignEnv('QFINAN') || isApp()
}

export default nativeCheck